package com.jic.manager.utils;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.common.utils.HttpClientUtils;
import com.jic.enums.RedisKey;
import com.jic.manager.enums.UccUrlEnums;
import com.jic.manager.enums.UucLoginSource;
import com.jic.manager.request.CheckImageRequest;
import com.jic.manager.request.UccUserRequest;
import com.jic.manager.request.UucUserLoginRequest;
import com.jic.manager.response.UccUserResponse;
import com.jic.manager.response.UucImageResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调用ucc公共请求方法
 * @author wwb
 */
@Slf4j
@Component
@RefreshScope
public class UccHttpUtils{

    @Value("${uuc.host}")
    private String host;
    /**
     * clientId
     */
    @Value("${uuc.clientId}")
    private String clientId;
    /**
     * secret
     */
    @Value("${uuc.clientSecret}")
    private String clientSecret;

    @Resource
    private RedisClientTemplate redisClientTemplate;

    private void getHeader(){
        HashMap<String, String> headerMap = new HashMap<>(1);
        headerMap.put("Authorization","Bearer "+redisClientTemplate.get(RedisKey.UCC_ACCESS_TOKEN.getName()));
        HttpClientUtils.setHeader(headerMap);
    }


    public Map<String,Object> getAccessToken(){
        try {
            HashMap<String, Object> param = new HashMap<>();
            param.put("client_id",clientId);
            param.put("client_secret",clientSecret);
            param.put("grant_type","client_credentials");
            String res = HttpClientUtils.doPost(host + UccUrlEnums.GET_ACCESS_TOKEN.getName(), param);
            if(StringUtils.isNotEmpty(res)){
                return JSONArray.parseObject(res,Map.class);
            }else{
                throw new Exception("获取AccessToken 返回为空");
            }
        }catch (Exception e){
            log.error("获取accessToken失败===>>>",e.getLocalizedMessage());
            return new HashMap<>(0);
        }
    }


    public List<UccUserResponse> getUccUserListByEmployinfo(UccUserRequest uccUserRequest) {
        try {
            HashMap<String, Object> param = new HashMap<>(1);
            param.put("employinfo",uccUserRequest.getEmployinfo());
            getHeader();
            String res = HttpClientUtils.doPost(host + UccUrlEnums.GET_UCC_USER.getName(), param);
            if(StringUtils.isNotEmpty(res)){
                try {
                    List<UccUserResponse> userResponseList =  JSONArray.parseObject(res,List.class);
                    return userResponseList;
                }catch (Exception e){
                    Map errorMsg = JSONArray.parseObject(res, Map.class);
                    throw new Exception(errorMsg.get("error_description").toString());
                }
            }else{
                throw new Exception("查询ucc用户列表失败");
            }
        }catch (Exception e){
            log.error("查询ucc用户列表失败===>>>{}",e.getMessage());
            return new ArrayList<>();
        }
    }

    public RestResult<UucImageResponse> getUucImageCode() {
        try {
            HashMap<String, Object> param = new HashMap<>(0);
            getHeader();
            String res = HttpClientUtils.doPost(host + UccUrlEnums.GET_IMAGE_CODE.getName(), param);
            if(StringUtils.isNotEmpty(res)){
                try {
                    UucImageResponse uucImageResponse = JSONArray.parseObject(res, UucImageResponse.class);
                    return RestResult.success(uucImageResponse);
                }catch (Exception e){
                    Map errorMsg = JSONArray.parseObject(res, Map.class);
                    return RestResult.error("9999",errorMsg.get("error_description").toString());
                }
            }else{
                throw new Exception("获取UUC图片验证码失败");
            }
        }catch (Exception e){
            log.error("获取UUC图片验证码失败===>>>{}",e.getMessage());
            return RestResult.error("9999","服务器错误...");
        }
    }

    public RestResult<Boolean> checkImageCode(CheckImageRequest checkImageRequest) {
        try {
            HashMap<String, Object> param = new HashMap<>(2);
            param.put("captchaToken",checkImageRequest.getCaptchaToken());
            param.put("captchaAnswer",checkImageRequest.getCaptchaAnswer());
            getHeader();
            String res = HttpClientUtils.doPost(host + UccUrlEnums.CHECK_IMAGE_CODE.getName(), param);
            if (StringUtils.isNotEmpty(res)){
                Map<String,Object> checkResult = JSONArray.parseObject(res, Map.class);
                if (null == checkResult.get("success")){
                    return RestResult.error("5000",checkResult.get("error_description").toString());
                }else{
                    return RestResult.success(Boolean.valueOf(checkResult.get("success").toString()));
                }
            }else {
                throw new Exception("校验图片验证码失败");
            }
        }catch (Exception e){
            log.error("校验图片验证码失败===>>>{}",e.getMessage());
            return RestResult.error("9999","服务器错误...");
        }
    }

    public String uccUserLogin(UucUserLoginRequest uucUserLoginRequest) throws Exception {
        Map<String, Object> param = new HashMap<>(4);
        param.put("username",uucUserLoginRequest.getAccount());
        param.put("password",AesUtils.encrypt(uucUserLoginRequest.getPassword()));
        param.put("clientId",clientId);
        param.put("clientSecret",clientSecret);
        InetAddress localHost = InetAddress.getLocalHost();
        String hostAddress = localHost.getHostAddress();
        param.put("ip", hostAddress);
        param.put("source", UucLoginSource.INTERNAL_LOGIN.getName());
        getHeader();
        String res = HttpClientUtils.doPost(host + UccUrlEnums.UUC_USER_LOGIN.getName(), param);
        return res;
    }

    public String getUserTokenByCode(String code) throws Exception {
        Map<String,Object> param = new HashMap<>(1);
        param.put("authCode",code);
        getHeader();
        String res = HttpClientUtils.doPost(host + UccUrlEnums.UUC_USER_GET_TOKEN.getName(), param);
        return res;
    }


    public String getUserInfoByAccessToken(String accessToken) throws Exception {
        HashMap<String, String> headerMap = new HashMap<>(1);
        headerMap.put("Authorization","Bearer "+accessToken);
        HttpClientUtils.setHeader(headerMap);
        String res = HttpClientUtils.doGet(host + UccUrlEnums.UUC_USER_INFO_ACCESS_TOKEN.getName(),new HashMap<>(0));
        return res;
    }

    public String getUserInfoByTokenId(String tokenId) throws IOException {
        Map<String, Object> param = new HashMap<>(1);
        param.put("tokenId",tokenId);
        InetAddress localHost = InetAddress.getLocalHost();
        String hostAddress = localHost.getHostAddress();
        param.put("ip", hostAddress);
        getHeader();
        String res = HttpClientUtils.doPost(host + UccUrlEnums.UUC_USER_INFO_TOKEN_ID.getName(),param);
        return res;
    }

    public List<UccUserResponse> getUccUserListByPhone(UccUserRequest uccUserRequest) {
        try {
            HashMap<String, String> param = new HashMap<>(1);
            param.put("identifiers",uccUserRequest.getPhone());
            getHeader();
            String res = HttpClientUtils.doGet(host + UccUrlEnums.GET_UCC_USER_BY_PHONE.getName(), param);
            if(StringUtils.isNotEmpty(res)){
                try {
                    List<Map<String,Object>> userResponseList =  JSONArray.parseObject(res,List.class);
                    List<UccUserResponse> restList = new ArrayList<>();
                    userResponseList.forEach(userResponse->{
                        if(userResponse.get("userId") != null && !userResponse.get("userId").equals("null")){
                            UccUserResponse uccUserResponse = new UccUserResponse();
                            uccUserResponse.setPhone(userResponse.get("identifier").toString());
                            uccUserResponse.setEmpName(userResponse.get("nickname") == null ? "null" : userResponse.get("nickname").toString());
                            uccUserResponse.setThridUserId(String.valueOf(userResponse.get("userId")));
                            restList.add(uccUserResponse);
                        }
                    });
                    return restList;
                }catch (Exception e){
                    Map errorMsg = JSONArray.parseObject(res, Map.class);
                    throw new Exception(errorMsg.get("error_description").toString());
                }
            }else{
                throw new Exception("根据手机号查询ucc用户列表");
            }
        }catch (Exception e){
            log.error("根据手机号查询ucc用户列表失败===>>>{}",e);
            return new ArrayList<>();
        }
    }
}
